<?php


namespace Tool\Controller;

use Think\Controller;

class CommonController extends Controller
{


    public function _initialize()
    {
        header("Content type:text/html;charset=utf-8");
        //加载配置
        $config = M('system_config')->where(array('id' => 1))->find();
        $this->assign('config', $config);

        if (!check_admin_login() && ACTION_NAME != "jihuo")
        {// 还没登录 跳转到登录页面
            $this->redirect('/Relay/login');
        }

    }

    /**
     * 获取当前Action名称
     * @access protected
     */
    protected function getActionName()
    {

        // 获取Action名称
        return substr(get_class($this), 0, -10);

    }


    public function index()
    {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter'))
        {
            $this->_filter($map);
        }
        $name = $this->getActionName();
        //dump($name);die();
        $model = CM($name);
        if (!empty ($model))
        {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    /**
     * +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     * +----------------------------------------------------------
     * @access protected
     * +----------------------------------------------------------
     * @param string $name 数据对象名称
     * +----------------------------------------------------------
     * @return HashMap
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    protected function _search()
    {
        //生成查询条件
        $name = $this->getActionName();
        $model = CM($name);
        $map = array();
        foreach ($model->getDbFields() as $key => $val)
        {
            if (isset ($_REQUEST [$val]) && $_REQUEST [$val] != '')
            {
                $map [$val] = $_REQUEST [$val];
            }
        }
        return $map;

    }


    /**
     * +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     * +----------------------------------------------------------
     * @access protected
     * +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
     * +----------------------------------------------------------
     * @return void
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = true)
    {
        $pk = $model->getPk();
        $dbArray = $model->getDbFields();
        unset($dbArray['_autoinc']);        // _autoinc 表示主键是否自动增长类型
        unset($dbArray['_pk']);            //_pk 表示主键字段名称
        $order = "";
        if (in_array("sort", $dbArray))
        {
            $order .= "sort desc,";
        }
        $order .= $pk . " desc";
        //取得满足条件的记录数
        $count = $model->where($map)->count($pk);
        //echo $model->getLastsql();
        if ($count > 0)
        {

            //创建分页对象
            if (!empty ($_REQUEST ['pagesize']))
            {
                $pagesize = $_REQUEST ['pagesize'];
            } else
            {
                $pagesize = C('PAGESIZE');
            }

            $p =  new \Think\Page($count, $pagesize);
            //分页查询数据
            $voList = $model->where($map)->order($order)->limit($pagesize)->page($_REQUEST[C('VAR_PAGE')])->select();
           // echo $model->getLastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val)
            {
                if (!is_array($val))
                {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //模板赋值显示
            $this->assign('list', $voList);
            //$this->assign('sort', $sort);
            $this->assign('order', $order);
            //$this->assign('sortImg', $sortImg);
            //$this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }

        //zhanghuihua@msn.com
        $this->assign('totalCount', $count);
        $this->assign('pagesize', $pagesize); //每页显示多少条
        $this->assign('currentPage', !empty($_REQUEST[C('VAR_PAGE')]) ? $_REQUEST[C('VAR_PAGE')] : 1);

        cookie('_currentUrl_', __SELF__);
        return;
    }

    function insert()
    {
        //B('FilterString');
        $name = $this->getActionName();
        $model = CM($name);
        if (false === $model->create())
        {
            $this->error($model->getError());
        }
        //保存当前数据对象
        $list = $model->add();
        if ('AdminRole' === $name)
        {
            M('AdminAccess')->add(array('role_id' => $list, 'node_id' => 1, 'level' => 1, 'pid' => 0));
            M('AdminAccess')->add(array('role_id' => $list, 'node_id' => 10, 'level' => 2, 'pid' => 1));
            M('AdminAccess')->add(array('role_id' => $list, 'node_id' => 14, 'level' => 3, 'pid' => 10));
            M('AdminAccess')->add(array('role_id' => $list, 'node_id' => 13, 'level' => 3, 'pid' => 10));
        }
        if ($list !== false)
        { //保存成功

            $sql = $model->getLastSql();
            M('admin_logs')->add(array(
                'vc_module' => $name,
                'vc_operation' => $sql,
                'creator_id' => $_SESSION[C('USER_AUTH_KEY')],
                'creator_name' => $_SESSION['loginUserName'],
                'vc_ip' => get_client_ip(),
                'status' => 1,
                'createtime' => time()
            ));


            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('新增成功!');
        } else
        {
            //失败提示
            $this->error('新增失败!');
        }
    }

    public function add()
    {
        $this->display();
    }

    function read()
    {
        $this->edit();
    }

    function edit()
    {
        $name = CONTROLLER_NAME;
        //echo "name={$name}";
        $model = D($name);
        //	dump($model);
        $pk = $model->getPk();
        $id = $_REQUEST[$pk];
        $vo = $model->where("{$pk}={$id}")->find();
        //echo $model->getLastSql();
        //dump($vo);
        $this->assign('vo', $vo);
        $this->display();
    }

    function update()
    {

        //B('FilterString');
        $name = $this->getActionName();
        $model = CM($name);
        if (false === $model->create())
        {
            $this->error($model->getError());
        }
        // 更新数据
        $list = $model->save();
        //echo $model->getLastSql();die();
        if (false !== $list)
        {
            //成功提示

            $sql = $model->getLastSql();
            M('admin_logs')->add(array(
                'vc_module' => $name,
                'vc_operation' => $sql,
                'creator_id' => $_SESSION[C('USER_AUTH_KEY')],
                'creator_name' => $_SESSION['loginUserName'],
                'vc_ip' => get_client_ip(),
                'status' => 1,
                'createtime' => time()
            ));


            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('编辑成功!');
        } else
        {
            //错误提示
            $this->error('编辑失败!');
        }
    }

    /**
     * +----------------------------------------------------------
     * 默认删除操作
     * +----------------------------------------------------------
     * @access public
     * +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    public function delete()
    {
        //删除指定记录
        $name = $this->getActionName();
        $model = M($name);
        if (!empty ($model))
        {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset ($id))
            {
                $condition = array($pk => array('in', explode(',', $id)));
                $list = $model->where($condition)->setField('status', -1);
                if ($list !== false)
                {
                    $this->success('删除成功！');
                } else
                {
                    $this->error('删除失败！');
                }
            } else
            {
                $this->error('非法操作');
            }
        }
    }

    public function foreverdelete()
    {
        //删除指定记录
        $name = $this->getActionName();
        if ($name == 'Article')
        {
            $name = 'ZbArticle';
        }
        $model = CM($name);
        if (!empty ($model))
        {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];

            if (isset ($id))
            {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete())
                {
                    if ('AdminRole' == $name)
                    {
                        M('AdminAccess')->where(array('role_id' => $id))->delete();
                        M('AdminRoleUser')->where(array('role_id' => $id))->delete();
                    }

                    $sql = $model->getLastSql();
                    M('admin_logs')->add(array(
                        'vc_module' => $name,
                        'vc_operation' => $sql,
                        'creator_id' => $_SESSION[C('USER_AUTH_KEY')],
                        'creator_name' => $_SESSION['loginUserName'],
                        'vc_ip' => get_client_ip(),
                        'status' => 1,
                        'createtime' => time()
                    ));


                    $this->success('删除成功！');
                } else
                {
                    $this->error($model->getlastsql());
                }
            } else
            {
                $this->error('非法操作');
            }
        }
        $this->forward();
    }


    /**
     * +----------------------------------------------------------
     * 添加删除操作  (多个删除)
     * +----------------------------------------------------------
     * @access public
     * +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */

    public function delAll()
    {
        $name = $this->getActionName();
        $model = CM($name);
        $pk = $model->getPk();
        $data[$pk] = array('in', $_POST['ids']);
        $model->where($data)->delete();
        $this->success('批量删除成功');
    }

    public function clear()
    {
        //删除指定记录
        $name = $this->getActionName();
        $model = CM($name);
        if (!empty ($model))
        {
            if (false !== $model->where('status=-1')->delete())
            { // zhanghuihua@msn.com change status=1 to status=-1
                $this->assign("jumpUrl", $this->getReturnUrl());
                $this->success(L('_DELETE_SUCCESS_'));
            } else
            {
                $this->error(L('_DELETE_FAIL_'));
            }
        }
        $this->forward();
    }

    /**
     * +----------------------------------------------------------
     * 默认禁用操作
     *
     * +----------------------------------------------------------
     * @access public
     * +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws FcsException
    +----------------------------------------------------------
     */
    public function forbid()
    {
        $name = $this->getActionName();
        $model = CM($name);
        $pk = $model->getPk();
        $id = $_REQUEST [$pk];

        $condition = array($pk => array('in', $id));
        $list = $model->forbid($condition);
        if ($list !== false)
        {
            //echo $this->getReturnUrl();die();
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态禁用成功');
        } else
        {
            //$this->error  (  '状态禁用失败！' );
            //$this->error()'
            die(dump($model->getlastsql()));
        }
    }

    public function checkPass()
    {
        $name = $this->getActionName();
        $model = CM($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->checkPass($condition))
        {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态批准成功！');
        } else
        {
            $this->error('状态批准失败！');
        }
    }

    public function recycle()
    {
        $name = $this->getActionName();
        $model = CM($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->recycle($condition))
        {

            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态还原成功！');

        } else
        {
            $this->error('状态还原失败！');
        }
    }

    public function recycleBin()
    {
        $map = $this->_search();
        $map ['status'] = 0;
        $name = $this->getActionName();
        $model = CM($name);
        if (!empty ($model))
        {
            $this->_list($model, $map);
        }
        $this->display();
    }

    /**
     * +----------------------------------------------------------
     * 默认恢复操作
     *
     * +----------------------------------------------------------
     * @access public
     * +----------------------------------------------------------
     * @return string
    +----------------------------------------------------------
     * @throws FcsException
    +----------------------------------------------------------
     */
    function resume()
    {
        //恢复指定记录
        $name = $this->getActionName();
        $model = CM($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        $model->resume($condition);
        if (false !== $model->resume($condition))
        {

            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态恢复成功！');
        } else
        {
            $this->error('状态恢复失败！');
        }
    }


    function saveSort()
    {
        $seqNoList = $_POST ['seqNoList'];
        if (!empty ($seqNoList))
        {
            //更新数据对象
            $name = $this->getActionName();
            $model = CM($name);
            $col = explode(',', $seqNoList);
            //启动事务
            $model->startTrans();
            foreach ($col as $val)
            {
                $val = explode(':', $val);
                $model->id = $val [0];
                $model->sort = $val [1];
                $result = $model->save();
                if (!$result)
                {
                    break;
                }
            }
            //提交事务
            $model->commit();
            if ($result !== false)
            {
                //采用普通方式跳转刷新页面
                $this->success('更新成功');
            } else
            {
                $this->error($model->getError());
            }
        }
    }

}